<template>
  <div class="patient-container">
    <h1>患者信息</h1>
    <!-- 检查用户信息是否加载完成 -->
    <div v-if="userInfo" style="width: 90%;align-content: center;">
      <el-form :model="userInfo" label-width="100px">
        <el-form-item label="患者Id">
          <el-input v-model="userInfo.patient.patientId" disabled></el-input>
        </el-form-item>
        <el-form-item label="患者姓名">
          <el-input v-model="userInfo.patient.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="患者年龄">
          <el-input v-model="userInfo.patient.age" disabled></el-input>
        </el-form-item>
        <el-form-item label="患者性别">
          <el-input v-model="userInfo.patient.sex" disabled></el-input>
        </el-form-item>
        <el-form-item label="患者联系电话">
          <el-input v-model="userInfo.patient.contactNumber" disabled></el-input>
        </el-form-item>
      </el-form>
      根据患者id查询:
      <el-input
          v-model="searchQuery"
          placeholder="请输入患者id进行搜索"
          clearable
          style="width: 300px; margin-left: 16px"
          @input="handleSearch"
      >
        <template #prefix>
          <el-icon>
            <search/>
          </el-icon>
        </template>
      </el-input>
    </div>
    <div v-else>
      加载中...
    </div>
    <!-- 编辑用户信息对话框 -->
    <el-dialog v-model="dialogFormVisible" title="编辑患者信息" width="500">
      <el-form :model="editUser.patient" :rules="rules" ref="formRef" label-position="right" label-width="auto">
        <el-form-item label="患者姓名" prop="name">
          <el-input v-model="editUser.patient.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="患者年龄" prop="age">
          <el-input v-model.number="editUser.patient.age" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="患者性别" prop="sex">
          <el-input v-model="editUser.patient.sex" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="患者联系电话" prop="contactNumber">
          <el-input v-model="editUser.patient.contactNumber" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEdit">修改</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {ElMessage} from 'element-plus';
import axios from 'axios';
import {mapGetters} from 'vuex';
import {useRoute} from "vue-router";

export default {
  computed: {
    ...mapGetters(['getUserId']) // 假设 Vuex 中存储的是 patient_id
  },
  data() {
    return {
      searchQuery: "", // 搜索框内容
      userInfo: {
        user_id: null,
        username: '',
        patient: {
          patientId: null,
          name: '',
          age: null,
          sex: '',
          contactNumber: ''
        }
      },
      dialogFormVisible: false,
      editUser: {
        user_id: null,
        username: '',
        patient: {
          patientId: null,
          name: '',
          age: null,
          sex: '',
          contactNumber: ''
        }
      },
      rules: {
        'patient.name': [
          {required: true, message: '请输入患者姓名', trigger: 'blur'}
        ],
        'patient.age': [
          {required: true, message: '请输入患者年龄', trigger: 'blur'},
          {type: 'number', message: '患者年龄必须为数字值', trigger: 'blur'}
        ],
        'patient.sex': [
          {required: true, message: '请输入患者性别', trigger: 'blur'}
        ],
        'patient.contactNumber': [
          {required: true, message: '请输入患者联系电话', trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.setPatientInfo();
    // this.getPatientInfo();
  },
  methods: {

    // 处理搜索
    async handleSearch() {
      if (this.searchQuery === "") {
        return;
      }
      try {
        const res = await axios.get(`/api/wu_vue_2_test/Patient/getById?Id=${this.searchQuery}`);
        if (res.data.data.patientId === null) {
          ElMessage({
            message: "未查询到该id",
            type: "warning",
            plain: true,
          });
        } else {
          this.userInfo.patient = res.data.data; // 更新数据
          ElMessage({
            message: "查询成功",
            type: "success",
            plain: true,
          });
        }
      } catch (error) {
        console.error("搜索失败:", error);
        ElMessage({
          message: "搜索失败，请稍后重试",
          type: "error",
          plain: true,
        });
      }
    },
    async setPatientInfo() {
      const route = useRoute();
      const Id = route.query.id; // 获取传递过来的 id 参数
      if (Id) {
      try {
        const res = await axios.get(`/api/wu_vue_2_test/Patient/getById?Id=${Id}`);
        if (res.data.code === 200) {
          this.userInfo.patient = res.data.data;
          this.editUser.patient = {...this.userInfo.patient};
        } else {
          ElMessage.error(res.data.message);
        }
      } catch (error) {
        console.error('请求出错:', error);
        ElMessage.error('请求出错，请稍后重试');
      }}
    },
    async handleEdit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const res = await axios.post('/api/wu_vue_2_test/Patient/update', this.editUser.patient);
            if (res.data.code === 200) {
              this.userInfo.patient = {...this.editUser.patient};
              this.dialogFormVisible = false;
              ElMessage.success('修改成功');
            } else {
              ElMessage.error(res.data.message);
            }
          } catch (error) {
            console.error('修改数据失败:', error);
            ElMessage.error('修改数据失败，请稍后重试');
          }
        } else {
          console.log('表单验证不通过');
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.patient-container {
  padding: 20px;
}
</style>